package org.example;

import javax.servlet.*;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.logging.Logger;

@WebListener
public class RequestLoggingListener implements ServletRequestListener {
    private static final Logger logger = Logger.getLogger(RequestLoggingListener.class.getName());

    // 在请求开始时调用
    @Override
    public void requestInitialized(ServletRequestEvent sre) {
        HttpServletRequest request = (HttpServletRequest) sre.getServletRequest();
        LocalDateTime startTime = LocalDateTime.now();

        // 将开始时间存储到请求的属性中
        request.setAttribute("startTime", startTime);

        String method = request.getMethod();
        String uri = request.getRequestURI();
        String queryString = request.getQueryString() != null ? request.getQueryString() : "N/A";
        String clientIp = request.getRemoteAddr();
        String userAgent = request.getHeader("User-Agent");

        // 记录请求的初始信息
        logger.info(String.format("Request started at %s | Method: %s | URI: %s | Query: %s | Client IP: %s | User-Agent: %s",
                startTime, method, uri, queryString, clientIp, userAgent));
    }

    // 在请求结束时调用
    @Override
    public void requestDestroyed(ServletRequestEvent sre) {
        HttpServletRequest request = (HttpServletRequest) sre.getServletRequest();
        LocalDateTime startTime = (LocalDateTime) request.getAttribute("startTime");
        LocalDateTime endTime = LocalDateTime.now();

        // 计算处理时间
        long duration = java.time.Duration.between(startTime, endTime).toMillis();

        // 记录请求的结束信息和处理时间
        logger.info(String.format("Request ended at %s | Processing time: %d ms", endTime, duration));
    }
}
